import {ref, computed} from "vue";
import {defineStore} from "pinia";
import {useUserStore} from "@/store/modules/user";
import {getNewCartGoods} from "@/api/cart";
import {MergeLocalCart} from "@/api/cart";
import { findCartList_request, insertCart_request, deleteCart_request, updateCart_request, checkAllCart_request } from "@/api/cart";

// 购物车状态
export const useCartStore = defineStore("cart", () => {
    // 获取用户状态
    const userStore = useUserStore()

    const {profile} = userStore
    const list = ref([]);
    // 有效商品列表
    const validList = computed(() => list.value.filter(item => item.stock > 0 && item.isEffective))
    // 有效商品件数
    const validTotal = computed(() => validList.value.reduce((p, c) => p + c.count, 0))
    // 有效商品总金额
    const validAmount = computed(() => validList.value.reduce((p, c) => p + c.nowPrice * 100 * c.count, 0) / 100)

    // 无效商品列表
    const invalidList = computed(() => list.value.filter(item => !(item.stock > 0 && item.isEffective)))

    // 选中商品列表
    const selectedList = computed(() => validList.value.filter(item => item.selected))

    // 选中商品件数
    const selectedTotal = computed(() => selectedList.value.reduce((p, c) => p + c.count, 0))

    // 选中商品总金额
    const selectedAmount = computed(() => selectedList.value.reduce((p, c) => p + (c.nowPrice * 100 * c.count), 0) / 100)

    // 是否全选
    const isCheckAll = () => (validList.value.length === selectedList.value.length && selectedList.value.length !== 0)

    // 添加商品到购物车
    const insertCart = (goods) => {
        // eslint-disable-next-line
        return new Promise((resolve, reject) => {
            // 已登录
            if (profile.token) {
                insertCart_request(goods).then(()=>{
                    return findCartList_request()
                }).then(data=>{
                    setCartList(data.result)
                    resolve()
                })
            } else {
                // 寻找满足条件的索引
                const sameIndex = list.value.findIndex(item => item.skuId === goods.skuId)
                if (sameIndex >= 0) {
                    goods.count = list[sameIndex].count + goods.count
                    // 从sameIndex开始，删除一个元素，即删除sameIndex
                    list.value.splice(sameIndex, 1)
                }
                list.value.unshift(goods)
                resolve()
            }
        })
    }

    // 更新购物车
    const updateCart = (goods) => {
        return new Promise((resolve) => {
            if (profile.token) {
                updateCart_request(goods).then(()=>{
                    return findCartList_request()
                }).then((data)=>{
                    setCartList(data.result)
                    resolve()
                })
            } else {
                const updateGoods = list.value.find(item => item.skuId === goods.skuId)
                for (const key in goods) {
                    if (goods[key] !== null && goods[key] !== undefined && goods[key] !== '') {
                        updateGoods[key] = goods[key]
                    }
                }
                resolve()
            }
        })
    }
    // 删除购物车商品
    const deleteCart = (skuId) => {
        //eslint-disable-next-line
        return new Promise((resolve) => {
            if (profile.token) {
                deleteCart_request([skuId]).then(()=>{
                    return findCartList_request()
                }).then((data)=>{
                    setCartList(data.result)
                    resolve()
                })
            } else {
                const index = list.value.findIndex(item => item.skuId === skuId)
                list.value.splice(index, 1)
                resolve()
            }
        })
    }

    const findCartList = () => {
        return new Promise((resolve, reject) => {
            // 已登录
            if (profile.token) {
                findCartList_request().then(data=>{
                    setCartList(data.result)
                    resolve()
                })
            } else {
                const promiseArr = list.value.map(async item => {
                    return await getNewCartGoods(item.skuId)
                })
                Promise.all(promiseArr).then(dataArr => {
                    dataArr.forEach(async (data, i) => {
                        await updateCart({skuId: list.value[i].skuId, ...data.result})
                    })
                    resolve()
                }).catch(e => {
                    reject(e)
                })
            }
        })
    }

    const checkAllCart = (selected) => {
        return new Promise((resolve) => {
            if (profile.token) {
                const ids = validList.value.map(item=>item.skuId)
                checkAllCart_request({selected, ids}).then(()=>{
                    return findCartList_request()
                }).then((data)=>{
                    setCartList(data.result)
                    resolve()
                })
            } else {
                validList.value.forEach(async item => {
                    await updateCart({skuId: item.skuId, selected})
                })
                resolve()
            }
        })
    }

    // 批量删除选中商品
    const batchDeleteCart = (isClear) => {
        return new Promise((resolve) => {
            if(profile.token) {
                const ids = (isClear ? invalidList : selectedList).value.map(item=>item.skuId)
                deleteCart_request(ids).then(()=>{
                    return findCartList_request()
                }).then((data)=>{
                    setCartList(data.result)
                    resolve()
                })
            }else {
                (isClear ? invalidList : selectedList).value.forEach(async item=>{
                    await deleteCart(item.skuId)
                })
                resolve()
            }
        })
    }

    const updateCartSku = ({oldSkuId, newSku}) => {
        return new Promise((resolve) => {
            if(profile.token) {
                const oldGoods = list.value.find(item=>item.skuId === oldSkuId)
                deleteCart_request([oldSkuId]).then(()=>{
                    return insertCart_request({skuId:newSku.skuId, count:oldGoods.count})
                }).then((data)=>{
                    setCartList(data.result)
                    resolve()
                })
            }else {
                const oldGoods = list.value.find(item=>item.skuId === oldSkuId)
                deleteCart(oldSkuId).then(r => r)
                const {  skuId, price:nowPrice, inventory: stock, specsText: attrsText } = newSku
                const newGoods = {...oldGoods, skuId, nowPrice, stock, attrsText }
                insertCart(newGoods).then(r => r)
                resolve()
            }
        })
    }

    // 设置购物车列表
    const setCartList = (list) => {
        list.value = list
    }

    const mergeLocalCart = async () => {
        const cartList = validList.value.map(({skuId, selected, count}) => {
            return {skuId, selected, count}
        })
        await MergeLocalCart(cartList)
        setCartList([])
    }

    return {
        list,
        insertCart,
        validList,
        validAmount,
        validTotal,
        updateCart,
        findCartList,
        deleteCart,
        selectedList,
        invalidList,
        selectedTotal,
        selectedAmount,
        isCheckAll,
        checkAllCart,
        batchDeleteCart,
        updateCartSku,
        setCartList,
        mergeLocalCart
    }
})